/**
 * Created by zheng on 2018/1/14.
 */
var BlogDocumentModel = require('../entity/BlogDocumentModel')
var mongoose = require('mongoose')

var DbProperty = require('../util/dbProperty')
var cheerio = require('cheerio')

var fs = require('fs')
  , gm = require('gm');

const MAX_SIMPLEDOC_LENGTH = 500;
const PAGE_SIZE = 10;

mongoose.connect(DbProperty.blogDocumentConnectUrl);

exports.addBlogDocument = (data, callback) => {
  console.log('data', data);
  transferFirstPicToBase64String(data.document, (err, thumbString) => {
    if (!err) {
      let simpleDoc = transferDocumentToSimpleDoc(data.document);
      blog = new BlogDocumentModel({
        title: data.title,
        lastUpdateDate: new Date().toLocaleDateString(),
        document: data.document,
        simpleDoc: simpleDoc,
        thumb: thumbString,
      })
      blog.save((err, doc, numAffected) => {
        if (err) {

        } else if (numAffected === 1) {
          callback(doc);
        } else {

        }
      })
    }
    else {
      return null
    }
  })
}

exports.getBlogDocumentById = (data, callback) => {
  BlogDocumentModel.find({
    _id: data._id
  }, (err, doc) => {
    if (!err) {
      callback(doc);
    }
  })
}

exports.getAllBlogDocument = (data, callback) => {
  BlogDocumentModel.find({}, (err, doc) => {
    if (!err) {
      callback(doc);
    }
  })
}

exports.getBlogDocumentWithPageNumber = (data, callback) => {
  BlogDocumentModel.find({})
    .skip(data.page * PAGE_SIZE)
    .limit(PAGE_SIZE)
    .sort({'_id': -1})
    .exec((err, doc) => {
      callback(doc);
    });
}

exports.getBlogDocumentWithPrePage = (data, callback) => {
  BlogDocumentModel
    .find({'_id': {"$lt": data._id}})
    .limit(PAGE_SIZE)
    .sort({'_id': -1})
    .exec((err, doc) => {
      callback(doc);
    });
}

exports.getBlogDocumentWithNextPage = (data, callback) => {
  BlogDocumentModel
    .find({'_id': {"$gt": data._id}})
    .limit(PAGE_SIZE)
    .sort({'_id': -1})
    .exec((err, doc) => {
      callback(doc);
    });
}


exports.updateBlogDocument = (data, callback) => {
  //test id = 5a63629f4e7cc74454008051
  transferFirstPicToBase64String(data.doc, (err, thumbString) => {
    if (!err) {
      let simpleDoc = transferDocumentToSimpleDoc(data.doc);
      BlogDocumentModel.update({
        _id: data._id
      }, {
        $set: {
          title: data.title,
          document: data.document,
          lastUpdateDate: new Date().toLocaleDateString(),
          simpleDoc: simpleDoc,
          thumb: thumbString,
        }
      }, (err, doc) => {
        callback(doc);
      })
    }
    else {
      callback(err);
    }
  })
}

exports.deleteBlogDocumentById = (data, callback) => {
  BlogDocumentModel.remove({
    _id: data._id
  }, (err, doc) => {
    callback(doc);
  });
}
exports.transferImage = (data, callback) => {
  transferFirstPicToBase64String(data.document, (err, data) => {
    callback(data);
  });
}

let transferDocumentToSimpleDoc = (doc) => {

  let $ = cheerio.load(doc);
  let documentText = $.text();
  if (documentText.length > MAX_SIMPLEDOC_LENGTH) {
    documentText = documentText.splice(0, MAX_SIMPLEDOC_LENGTH);
  }
  return documentText;
}

let transferFirstPicToBase64String = (doc, callback) => {
  let $ = cheerio.load(doc);
  let imglist = $('img')
  imglist.each(function (index, item) {
    let picSrc = $(this).attr("src");
    if (picSrc.match(/^data:image\/\w+;base64,/)) {
      let base64Data = picSrc.replace(/^data:image\/\w+;base64,/, "")
      let dataBuffer = new Buffer(base64Data, 'base64');
      gm(dataBuffer)
        .resize('400', '400', '!')
        .toBuffer('jpeg', (err, buffer) => {
          let base64Buffer = null;
          if (buffer)
            base64Buffer = buffer.toString('base64');
          callback(err, base64Buffer);
          buffer = null;
        })
    }
  })
  if(!imglist || imglist.length===0){
    callback(null, null);
  }
}
